package com.royal.lr.util;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AliyunOssUtil {
    private static final Logger logger = LogManager.getLogger(AliyunOssUtil.class);

   private static String endpoint = "";
  private static String accessKeyId = "";
   private static String accessKeySecret = "";
    private static String bucketName = "";

    public static String upload(String key,String uploadFile)throws Exception{
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String ossUrl=null;
        try {
            UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, key);
            // 待上传的本地文件
            uploadFileRequest.setUploadFile(uploadFile);
            // 设置并发下载数，默认1
            uploadFileRequest.setTaskNum(5);
            // 设置分片大小，默认100KB
            uploadFileRequest.setPartSize(1024 * 1024 * 1);
            // 开启断点续传，默认关闭
            uploadFileRequest.setEnableCheckpoint(true);

            UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);
            Date expire= TimeUtil.addYear(new Date(),10);
            URL url=ossClient.generatePresignedUrl(bucketName,key,expire);
            String imgUrl=url.toString();
            int index=imgUrl.indexOf("/image");
            ossUrl=imgUrl.substring(0,index).replace("-internal","")+imgUrl.substring(index);
        } catch (OSSException oe) {
            throw new Exception("Error Message:"+oe.getErrorMessage()+", Error Code:"+oe.getErrorCode());
           /* System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());*/
        } catch (ClientException ce) {
            ce.printStackTrace();
            logger.error("oss client exception:"+ce.getMessage());
            throw new Exception(ce.getMessage());
        } catch (Throwable e) {
            throw new Exception(e);
        } finally {
            ossClient.shutdown();
        }
        return ossUrl;
    }


    public static String uploadFile(String key,File file)throws Exception{
        ClientConfiguration conf = new ClientConfiguration();

        // 设置HTTP最大连接数
        conf.setMaxConnections(5000);

        // 设置TCP连接超时
        conf.setConnectionTimeout(60000);

        // 设置最大的重试次数
        conf.setMaxErrorRetry(5);

        // 设置Socket传输数据超时的时间
        conf.setSocketTimeout(60000);

        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String ossUrl=null;
        try {
          ossClient.putObject(bucketName,key,file);
            Date expire= TimeUtil.addYear(new Date(),10);
            URL url=ossClient.generatePresignedUrl(bucketName,key,expire);
            String imgUrl=url.toString();
            int index=imgUrl.indexOf("/image");
            ossUrl=imgUrl.substring(0,index).replace("-internal","")+imgUrl.substring(index);
        } catch (OSSException oe) {
            throw new Exception("Error Message:"+oe.getErrorMessage()+", Error Code:"+oe.getErrorCode());
           /* System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());*/
        } catch (ClientException ce) {
            ce.printStackTrace();
            logger.error("oss client exception:"+ce.getMessage());
            throw new Exception(ce.getMessage());
        } catch (Throwable e) {
            throw new Exception(e);
        } finally {
            ossClient.shutdown();
        }
        return ossUrl;
    }


    public static  void download(String key,String downloadFile)throws Exception{
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        try {
            DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, key);
            // 设置本地文件
            downloadFileRequest.setDownloadFile(downloadFile);
            // 设置并发下载数，默认1
            downloadFileRequest.setTaskNum(5);
            // 设置分片大小，默认100KB
            downloadFileRequest.setPartSize(1024 * 1024 * 1);
            // 开启断点续传，默认关闭
            downloadFileRequest.setEnableCheckpoint(true);

            DownloadFileResult downloadResult = ossClient.downloadFile(downloadFileRequest);

           // ObjectMetadata objectMetadata = downloadResult.getObjectMetadata();
          //  System.out.println(objectMetadata);
             /*System.out.println(objectMetadata.getETag());
            System.out.println(objectMetadata.getLastModified());
            System.out.println(objectMetadata.getUserMetadata().get("meta"));*/
        } catch (OSSException oe) {
            throw new Exception("Error Message:"+oe.getErrorMessage()+", Error Code:"+oe.getErrorCode());
        } catch (ClientException ce) {
            throw new Exception(ce.getMessage());
        } catch (Throwable e) {
            throw new Exception(e);
        } finally {
            ossClient.shutdown();
        }
    }

    // 分页获取所有Object，每页maxKeys条Object
    public  static  List<String> listObject( int maxKeys)throws Exception{
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        List<String> keys = new ArrayList<>();
        try {
            ObjectListing objectListing = null;
            String nextMarker = null;
            List<OSSObjectSummary> sums = null;
            nextMarker = null;
            do {
                objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).
                        withMarker(nextMarker).withMaxKeys(maxKeys));

                sums = objectListing.getObjectSummaries();
                for (OSSObjectSummary s : sums) {
                    keys.add(s.getKey());
                }

                nextMarker = objectListing.getNextMarker();

            } while (objectListing.isTruncated());
        } catch (OSSException oe) {
            throw new Exception("Error Message:"+oe.getErrorMessage()+", Error Code:"+oe.getErrorCode());
        } catch (ClientException ce) {
            throw new Exception(ce.getMessage());
        } catch (Throwable e) {
            throw new Exception(e);
        } finally {
            ossClient.shutdown();
        }
        return keys;
    }

    public  static  List<String> listPrefixObject(String keyPrefix)throws Exception{
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        List<String> keys = new ArrayList<>();
        try {
            ObjectListing objectListing = null;
            List<OSSObjectSummary> sums = null;
            objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withPrefix(keyPrefix).withMaxKeys(1000));
            sums = objectListing.getObjectSummaries();

            for (OSSObjectSummary s : sums) {
                keys.add(s.getKey());
            }

        } catch (OSSException oe) {
            throw new Exception("Error Message:"+oe.getErrorMessage()+", Error Code:"+oe.getErrorCode());
        } catch (ClientException ce) {
            throw new Exception(ce.getMessage());
        } catch (Throwable e) {
            throw new Exception(e);
        } finally {
            ossClient.shutdown();
        }
        return keys;
    }

    // 删除创建的Object
    public  static  void deleteObject(List<String> keys)throws Exception{
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(
                    new DeleteObjectsRequest(bucketName).withKeys(keys));
        } catch (OSSException oe) {
            throw new Exception("Error Message:"+oe.getErrorMessage()+", Error Code:"+oe.getErrorCode());
        } catch (ClientException ce) {
            throw new Exception(ce.getMessage());
        } catch (Throwable e) {
            throw new Exception(e);
        } finally {
            ossClient.shutdown();
        }
    }
}
